package com.eliza.room.db.activity

import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eliza.room.R
import com.eliza.room.db.dao.StuRoomDatabase
import com.eliza.room.db.dao.StudentDao
import com.eliza.room.db.vm.StudentVm
import com.eliza.room.model.Student
import kotlinx.coroutines.launch


class RoomRecycleActivity : AppCompatActivity() {
    lateinit var studentDao: StudentDao
    lateinit var rrAdapter: RoomRecycleAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycle)
        val recycleView = findViewById<RecyclerView>(R.id.recycleView)
        recycleView.layoutManager = LinearLayoutManager(this)

        rrAdapter = RoomRecycleAdapter(
            listOf<Student>(Student("name", 12))
        )
        recycleView.adapter = rrAdapter
        studentDao = StuRoomDatabase.getInstance(this).studentDao as StudentDao


        val vmp = ViewModelProvider(
            this, ViewModelProvider.AndroidViewModelFactory(application)
        ).get(StudentVm::class.java)

        vmp.getAllStudentsLive().observe(this) {
            rrAdapter.stuList = it
            rrAdapter.notifyDataSetChanged()
        }
        findViewById<Button>(R.id.recycle_mDelete).setOnClickListener {
            lifecycleScope.launch {
                mDelete()
            }

        }

        findViewById<Button>(R.id.recycle_mUpdate).setOnClickListener {
            lifecycleScope.launch {
                mUpdate()
            }

        }
        findViewById<Button>(R.id.recycle_mInsert).setOnClickListener {
            lifecycleScope.launch {
                mInsert()
            }

        }
        findViewById<Button>(R.id.recycle_mQuery).setOnClickListener {
            lifecycleScope.launch {
                mQuery()
            }

        }
    }


    suspend fun mInsert() {
        val s1 = Student("Jack", 20)
        val s2 = Student("Rose", 18)
        studentDao.insertStu(s1, s2)
    }

    suspend fun mDelete() {
        val s1 = Student(2)
        studentDao.deleteStu(s1)

    }

    suspend fun mUpdate() {
        val s1 = Student(3, "Jason", 21)
        studentDao.updateStu(s1)
    }

    fun mQuery() {
        studentDao.getAllStuList()
    }


}